#include"thread_pool.h"

ThreadPool::ThreadPool(size_t n) : t_num_(n), stop_(false)
{
    for (int i = 0; i < t_num_; i++)
        threads_.emplace_back(
            [this](){
                while(true)
                {
                    function<void()> func;
                    {   // 加锁保护队列
                        unique_lock<mutex> lock(mutex_);

                        // 停止或者有新任务了
                        task_cv_.wait(lock, [this]()
                                        { return stop_ || task_que_.size(); });
                        
                        // 退出
                        if(stop_ && task_que_.empty())
                            break;

                        if(task_que_.empty())
                            continue;
                        
                        func = move(task_que_.front());
                        task_que_.pop();
                    }
                    func();
                }
            }
        );
}

ThreadPool::~ThreadPool()
{
    {
        unique_lock<mutex> lock(mutex_);
        // 结束
        stop_ = true;
        // 激活全部任务
        task_cv_.notify_all();
    }

    for (int i = 0; i < t_num_; i++)
        threads_[i].join(); // 回收
}

bool ThreadPool::start()
{
    return true;
}

void ThreadPool::add(const function<void()> &func)
{
    {
        unique_lock<mutex> lock(mutex_);
        task_que_.push(func);
    }
    task_cv_.notify_one();
}